<template>
    <!--  设计资料审批（资料审批）-->
    <!-- 审批通用页面组件 -->
    <div class="wrapper">
        <div class="title">审批</div>
        <title-name :title="processName + '-' + taskName" />
        <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
            <template>
                <title-name title="节点信息" />
                <slot name="extraResult" />
                <a-descriptions
                        class="mb20"
                        title=""
                >
                    <a-descriptions-item label="当前节点">
                        {{ taskName }}
                    </a-descriptions-item>
                    <a-descriptions-item label="审批人">
                        {{ currentUser.name }}
                    </a-descriptions-item>
                    <a-descriptions-item label="审批时间">
                        {{ currentTime }}
                    </a-descriptions-item>
                </a-descriptions>

                <title-name title="指定审核人员" />
                <div class="about-master-container">
                    <a-form-model :rules="rules" :model="form2" ref="form">
                        <a-row>
                            <a-col :span="8">
                                <a-form-model-item
                                        label="审核人员"
                                        prop="respEmployeeId"
                                >
                                    <a-select v-model="form2.respEmployeeId">
                                        <a-select-option :value="item.userId" v-for="item in departmentPersonList">{{ item.name }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                    </a-form-model>
                </div>

            </template>

            <slot name="extraOption" />

            <template>
                <title-name title="审批意见" />
                <a-form
                        ref="form1"
                        :form="form"
                >
                    <a-form-item class="approval-item">
                        <BaseTextarea
                                v-model="opinions"
                                placeholder="请填写审批意见"
                        />
                    </a-form-item>
                    <slot name="extraMiddle" />
                    <div class="overfloat">
                        <div class="floatRight">
                            <a-button
                                    type="primary"
                                    style="margin-right: 20px"
                                    @click="handleApprovalTransfer"
                            >
                                审批转移
                            </a-button>
                            <a-button
                                    v-if="buttonConfig.no.isShow"
                                    type="primary"
                                    style="margin-right: 20px"
                                    @click="handelUnApproval"
                            >
                                {{ buttonConfig.no.title }}
                            </a-button>
                            <a-button
                                    v-if="buttonConfig.ok.isShow"
                                    type="primary"
                                    @click="handelApproval"
                            >
                                {{ buttonConfig.ok.title }}
                            </a-button>
                        </div>
                    </div>
                </a-form>
            </template>

            <template>
                <title-name title="审批流程信息" />
                <div class="btns-wrapp mb20">
                    <a-button
                            type="primary"
                            @click="visibleState.auditProcess = true"
                    >
                        审批流程图
                    </a-button>
                </div>
                <a-spin
                        tip="流程信息加载中..."
                        :spinning="flowRequesting"
                />
                <a-table
                        :columns="columnApprove"
                        :data-source="approveInfos"
                        bordered
                >
          <span
                  slot="serial"
                  slot-scope="text, record, index"
          >{{ index + 1 }}</span>
                    <template
                            slot="opinions"
                            slot-scope="text, record, index"
                    >
                        <a-tooltip placement="topLeft">
                            <template slot="title">
                                <span> {{ text }}</span>
                            </template>
                            <span> {{ text }}</span>
                        </a-tooltip>
                    </template>
                </a-table>
            </template>
        </a-card>

        <slot name="extraAfter" />

        <ApprovalDetails
                :title="'审批流程信息'"
                :business-id="id"
                :visible="visibleState.auditProcess"
                @cancel="visibleState.auditProcess = false"
                @confirm="visibleState.auditProcess = false"
        />

        <AuditBusinessDetail v-if="isNeedDetails" />
    </div>
</template>

<script>
  import ApprovalDetails from '@/components/approvalDetails'
  import AuditBusinessDetail from '@/views/matters/AuditBusinessDetail'
  import { getFlowChart } from '@/api/process'
  import { getProcessNodeList, completeTask } from '@/api/process'
  import { getOneOrgUsers, getOrgEmployeesListBy } from '@/api/commons'
  import TreeSelectOrganization from '@/components/TreeSelectOrganization'
  import OrgStaffAsync from '@/components/TreeSelectOrganization/orgStaffAsync.vue'
  import Jobs from '@/components/TreeSelectOrganization/jobs'
  import moment from 'moment'
  import Vue from 'vue'
  import { notifyParentWindow } from '@/utils/util.js'

  const columnApprove = [
    {
      title: '序号',
      width: 80,
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '审批人',
      dataIndex: 'userName',
      ellipsis: true,
      width: 180
    },
    {
      title: '审批时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: 180
    },
    {
      title: '节点名称',
      dataIndex: 'taskName',
      ellipsis: true,
      width: 180
    },
    {
      title: '滞留时间',
      dataIndex: 'durationInMillis',
      ellipsis: true,
      width: 140
    },
    {
      title: '审批意见',
      dataIndex: 'formData.opinions',
      scopedSlots: { customRender: 'opinions' },
      ellipsis: true
    }
  ]

  export default {
    name: 'Approval',
    components: {
      AuditBusinessDetail,
      ApprovalDetails
    },
    props: {
      text: String,
      /**
       * 审批时的回调，返回false时，会阻止审批；返回true时，则正常进行后续流程
       * @param {String} flag enum: 'approval' || 'unApproval'   通过 || 不通过
       */
      callbackFn: {
        type: [Function, Object],
        default: null
      },
      /*
       * 提交之后
       * */
      beforeSubmitFn: {
        type: [Function, Object],
        default: null
      },
      submitData: {
        type: Object,
        default() {
          return {}
        }
      },
      buttonConfig: {
        type: Object,
        default() {
          return {
            no: {
              isShow: true,
              title: '审批不通过'
            },
            ok: {
              isShow: true,
              title: '审批通过'
            }
          }
        }
      },
      isNeedDetails: {
        type: Boolean,
        default() {
          return true
        }
      }
    },
    data() {
      return {
        rules: {
          respEmployeeId: [{ required: true, message: '请选择审核人员', trigger: 'change' }]
        },
        departmentPersonList: [],
        visibleState: {
          auditProcess: false
        },
        flowChart: '', // 流程图base64
        loading: {
          flowChart: false
        },
        form: {
          orgSelectedName: '',
          orgSelectedLabel: '',
          jobsSelectedName: undefined, //岗位
          respEmployeeId: undefined //人员
        },
        form2: {
          respEmployeeId: undefined //人员
        },
        treeCheckable: true,

        childrenNode: 'jobs',

        columnApprove,
        opinions: '',
        approveInfos: [], // 审批流程信息
        procInstId: '', //当前流程实例ID
        taskId: '', //当前流程节点ID
        processName: '', //流程名称
        taskName: '', //当前流程节点名称
        taskDefKey: '', //任务标识
        currentTime: '', //当前审批时间
        currentUser: '', //当前审批人
        flowRequesting: false,
        detailUrl: null, //详情地址

        assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
        assignCode: '', //候选组编码 岗位编码
        assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
        businessType: '' //业务类型 0 项目
      }
    },
    computed: {},
    created() {
      const {
        type,
        code,
        level,
        btype,
        businessId,
        procInstId,
        name,
        processName,
        detailUrl,
        taskId,
        taskDefKey
      } = this.$route.query
      if (type) {
        this.assignType = type
        this.assignCode = code
        this.assignLevel = level
        this.businessType = btype
      }
      this.id = businessId
      if (!this.id) {
        this.$error({ content: '无指定业务ID，将自动关闭' })
        setTimeout(() => {
          window.close()
        }, 1500)
        return
      }
      this.procInstId = procInstId
      this.taskName = decodeURIComponent(name)
      this.processName = decodeURIComponent(processName)
      document.title = this.processName + '-' + this.taskName
      if (detailUrl) {
        this.detailUrl = decodeURIComponent(detailUrl)
      }
      // else {
      //     this.detailUrl = '/process/auditBusinessDetail'
      // }
      this.taskId = taskId
      this.taskDefKey = taskDefKey
      this.currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
      this.currentUser = Vue.getAcloudProvider().getUserInfo()
      //获取流程节点执行情况
      this.getProcessNodes()
      this.getDepartmentPersonList()
    },
    mounted() {
      this.getFlowChartReq()
    },
    methods: {
      async getDepartmentPersonList() {
        let res = await getOneOrgUsers({
          pageSize: 10000,
          pageNo: 1,
          queryPostRelation: true,
          rootOrgId: this.$currentPost().deptId
        })
        if (res.code === this.SUCCESS_CODE) {
          console.log(res.data)
          this.departmentPersonList = res.data.list
        }
      },
      getFlowChartReq() {
        this.loading.flowChart = true
        getFlowChart(this.id)
          .then((res) => {
            this.loading.flowChart = false
            if (res.code === 200) {
              this.flowChart = 'data:image/png;base64,' + res.data
            }
          })
          .catch(() => {
            this.loading.flowChart = false
          })
      },
      getProcessNodes() {
        this.flowRequesting = true
        getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
          .then((res) => {
            if (res.code === 200) {
              const data = res.data
              const userIds = data.map((d) => {
                if (d.formData) {
                  d.formData = JSON.parse(d.formData)
                }
                return d.assignee
              })
              getOrgEmployeesListBy({ userIds, delete: true }).then((employees) => {
                this.flowRequesting = false
                res.data.forEach((r) => {
                  employees.data.some((e) => {
                    if (e.userId === r.assignee) {
                      r.userName = e.name
                      return true
                    }
                  })
                })
                this.approveInfos = res.data
              })
            }
          })
          .catch(() => {
            this.flowRequesting = false
          })
      },
      submit(reject, assign = {}) {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        const data = {
          formData: {
            opinions: this.opinions,
            reject,
            projectId: '',
            postId: userInfo?.currentPost?.postId || '',
            postCode: userInfo?.currentPost?.postCode || ''
          },
          assignTypeEnum: this.assignType, //指派类型
          assgins: this.form.respEmployeeId, //人员
          groupEnum: this.form.jobsSelectedName, //岗位
          procInstId: this.procInstId,
          taskId: this.taskId,
          userId: this.currentUser.id
        }
        console.log(data)
        const variable = {}
        // return;
        if (reject) {
          variable.reject = true
        } else {
          variable.reject = false
        }

        data.variables = {
          ...variable,
          ...this.submitData, // 特殊流程的数据，转交给审批,
          ...assign,
        }

        return completeTask(data)
          .then((res) => {
            if (res.status === 200) {
              notifyParentWindow() // 通知父窗口
              // this.$success({
              //   content: '审批提交成功，即将自动关闭当前窗口',
              //   onOk() {
                  window.close()
              //   }
              // })
              // setTimeout(() => {
              //   window.close()
              // }, 2000)
            } else {
              this.$error({ content: '审批提交失败，请稍后重试' })
            }
            return res
          })
          .catch((err) => {
            return err
          })
      },
      async handleApprovalTransfer() {
        this.$refs.form.validate(async valid => {
          if (valid) {
            this.$submitConfirm(async () => {
              await this.submit(false, {
                assignVariableType: 1,
                assignVariableValue: this.form2.respEmployeeId,
                transfer: 1
              })
            },'确定转移？')
          } else {
            this.$noticeWarning('请选择审核人员')
          }
        })

      },
      async handelUnApproval() {
        this.$bus.$emit('handelUnApproval')
        const callbackFn = this.callbackFn
        if (callbackFn && !callbackFn('unApproval')) return

        //remark2020/12/31 修改下面的方法请同步修改handelUnApprovalCopy方法
        // 审批不通过
        if (!this.opinions) {
          this.$warning({ content: '请填写审批意见' })
          return
        }
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批不通过？',
          okType: 'danger',
          onOk: async () => {
            if (this.beforeSubmitFn) {
              if (!(await this.beforeSubmitFn({ agree: false, opinion: this.opinions }))) {
                return
              }
            }
            return new Promise((resolve, reject) => {
              this.submit(true, { transfer: 0 })
                .then(() => {
                  resolve()
                  confirmWin.destroy()
                })
                .catch(() => reject)
            }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
          },
          onCancel: () => {
          }
        })
      },
      async handelUnApprovalCopy() {
        // 审批不通过
        if (!this.opinions) {
          this.$warning({ content: '请填写审批意见' })
          return
        }
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批不通过？',
          okType: 'danger',
          onOk: async () => {
            if (this.beforeSubmitFn) {
              if (!(await this.beforeSubmitFn({ agree: false, opinion: this.opinions }))) {
                return
              }
            }
            return new Promise((resolve, reject) => {
              this.submit(true)
                .then(() => {
                  resolve()
                  confirmWin.destroy()
                })
                .catch(() => reject)
            }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
          },
          onCancel: () => {
          }
        })
      },

      async handelApproval() {
        this.$bus.$emit('handelApproval')
        const callbackFn = this.callbackFn
        console.log(callbackFn)
        if (callbackFn && !callbackFn('approval')) return

        //remark2020/12/31 修改下面的方法请同步修改handelApprovalCopy方法
        // 审批通过
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批通过？',
          okType: 'danger',
          onOk: async () => {
            if (this.beforeSubmitFn) {
              if (!(await this.beforeSubmitFn({ agree: true, opinion: this.opinions }))) {
                return
              }
            }
            return new Promise((resolve, reject) => {
              this.submit(false, { transfer: 0 })
                .then(() => {
                  resolve()
                  confirmWin.destroy()
                })
                .catch(() => reject)
            }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
          },
          onCancel() {
          }
        })
      },
      async handelApprovalCopy() {
        // 审批通过
        const _this = this
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批通过？',
          okType: 'danger',
          onOk: async () => {
            if (this.beforeSubmitFn) {
              if (!(await this.beforeSubmitFn({ agree: true, opinion: this.opinions }))) {
                return
              }
            }
            return new Promise((resolve, reject) => {
              this.submit(false)
                .then(() => {
                  resolve()
                  confirmWin.destroy()
                })
                .catch(() => reject)
            }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
          },
          onCancel() {
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
    .img-wrapper {
        padding: 10px 0;
    }

    .wrapper {
        padding: 20px;

        .title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
        }

        /deep/ .approval-item .ant-form-item-control-wrapper {
            width: 100%;
        }
    }

    .wrapper-row {
        padding-left: 55px;
        font-weight: bold;
        letter-spacing: 1px;
    }

    /deep/ .ant-form-item label {
        font-size: 12px;
    }

    /deep/ .ant-btn {
        border-radius: 5px;
    }

    /deep/ .ant-input {
        /*width: 70%;*/
        border-radius: 5px;
    }

    /deep/ .ant-card.ant-card-bordered {
        border-radius: 5px;
    }

    .ant-avatar-lg {
        width: 48px;
        height: 48px;
        line-height: 48px;
    }

    .list-content-item {
        color: rgba(0, 0, 0, 0.45);
        display: inline-block;
        vertical-align: middle;
        font-size: 14px;
        margin-left: 40px;

        span {
            line-height: 20px;
        }

        p {
            margin-top: 4px;
            margin-bottom: 0;
            line-height: 22px;
        }
    }

    .title-name {
        border-left: 5px solid #1890ff;
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 20px;
        padding-left: 15px;
        height: 20px;
        line-height: 20px;
    }

    /deep/ .table-page-search-wrapper .ant-form-inline .ant-row .ant-col.ant-col-sm-24.ant-col-md-12 {
        padding-left: 80px;
    }

    /deep/ .ant-form-item .ant-form-item-control-wrapper {
        /*width: 100%;*/
    }

    /deep/ .col .ant-form-item .ant-form-item-control-wrapper {
        width: calc(100% - 135px);
    }
</style>

